﻿#region Copyright

// /*
// SilverlightInEnterprise
// SilverlightInEnterprise.SharedCode.Repository
// OrderItem.cs
// 
// Author: Matt Van Horn
// Created 11/17/2011 3:15 PM
// Copyright: Silverlight in the Enterprise www.slinenterprise.com
// 
// Licensed under MS-PL http://www.opensource.org/licenses/MS-PL and while you 
// may use this in anyway you see fit and owe us nothing to do so, we wouldn't mind knowing that you got value out of the work we did (so we will do more) so 
// we ask that you leave a comment on www.slinenterprise.com or on the codeplex site slinenterprise.codeplex.com
// 
// */

#endregion

using System.Runtime.Serialization;
using SilverlightInEnterprise.SharedCode.Repository.Cache;

namespace SilverlightInEnterprise.SharedCode.Repository.Models
{
    [DataContract]
    public partial class OrderItem
    {
        private const string DISPLAY_FORMAT = "{0} {1}: {2}";

        [DataMember]
        public int Id { get; set; }

        [DataMember]
        public int OrderId { get; set; }

        [DataMember]
        public int ProductId { get; set; }

        [DataMember]
        public int Units { get; set; }

        [DataMember]
        public decimal PricePerUnit { get; set; }

        public string ProductName
        {
            get
            {
                string display = null;
                if (this.product != null)
                    display = product.Name;
                return display;
            }
        }

        private Product product;

        public Product Product
        {
            get
            {
                bool needProduct = product == null;
                if (!needProduct)
                    needProduct = product.Id != this.ProductId;
                if (needProduct)
                    this.product = ProductCache.Cache.GetItemByKey(this.ProductId);
                return this.product;
            }
        }

        public decimal Total
        {
            get { return this.PricePerUnit*this.Units; }
        }

        public override string ToString()
        {
            string display = base.ToString();
            if (this.product != null)
            {
                display = string.Format(DISPLAY_FORMAT, this.Units, ProductName, this.Total);
            }
            return display;
        }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            return this.Id == (obj as OrderItem).Id;
        }
    }
}